
const sequelize = require('../config/operateDB');
const {Sequelize, DataTypes, Op} = require('sequelize');
const {setSession, getRequestParams} = require('../utils/utils');
const {wxUrl} = require('../config/wxUrl');
const axios = require('axios');
const {wxConfig} = require('../config/wxConfig');

const User = sequelize.define('user', {
    id: {
        type: DataTypes.UUID,
        allowNull: false,
        primaryKey: true,
        defaultValue: Sequelize.UUIDV4,
    },
    nickName: {
        type: DataTypes.TEXT,
        allowNull: true,
    },
    // 用户头像。可以是自己上传 也可以是微信的头像
    avatarUrl: {
        type: DataTypes.TEXT,
        allowNull: false,
    },
    gender: {
        type: DataTypes.INTEGER,
        allowNull: false,
    },
    province: {
        type: DataTypes.TEXT,
        allowNull: true,
    },
    city: {
        type: DataTypes.TEXT,
        allowNull: true,
    },
    country: {
        type: DataTypes.TEXT,
        allowNull: true,
    },
    openId: {
        type: DataTypes.TEXT,
        allowNull: false,
    },
    wechatCode: {
        type: DataTypes.TEXT,
        allowNull: true,
    },
    teacher: {
        type: DataTypes.TEXT,
        allowNull: false,
    },
    // 记住的单词数量
    rememberWords: {
        type: DataTypes.BIGINT,
        allowNull: true,
    },
    historyVideoIds: {
        type: DataTypes.STRING,
        allowNull: true
    },
    historyNews: {
        type: DataTypes.STRING,
        allowNull: true
    }
}, {

});

const Teacher = sequelize.define('teachers', {
    id: {
        type: DataTypes.UUID,
        allowNull: false,
        primaryKey: true,
        defaultValue: Sequelize.UUIDV4,
    },
    name: {
        type: DataTypes.TEXT,
        allowNull: true,
    },
    // 年龄 0 女，1 男。
    gender: {
        type: DataTypes.INTEGER,
        allowNull: false,
    },
}, {

});


async function initTeacher() {
    await Teacher.sync();
    await User.sync();
    const count = await Teacher.count();
    if (0 === count) {
        const teachers = [
            {
                name: '张三',
                gender: 1,
                age: '25',
            },
            {
                name: '李四',
                gender: 0,
                age: '28',
            },
            {
                name: '王二',
                gender: 1,
                age: '30',
            },
            {
                name: '周杰伦',
                gender: 0,
                age: '35',
            },
            {
                name: '菜菜',
                gender: 1,
                age: '29',
            },
            {
                name: '罗洋',
                gender: 0,
                age: '55',
            },
        ];
        await Teacher.bulkCreate(teachers);
        console.log('初始化老师成功！');
    }
}
initTeacher();

const usersModel = {

    checkParams(ctx, params) {
        if (!params.code) {
            ctx.errorParams('微信的临时登录凭证为空！');
            return false;
        } 
        // else if (!params.userInfo) {
        //     ctx.errorParams('用户信息为空！');
        //     return false;
        // }
         else  {
            return true;
        }
    },
    async login(ctx) {
        const params = getRequestParams(ctx);
        
        var isValid = this.checkParams(ctx, params);
        if (!isValid)  return;

        const res = await axios.get(wxUrl.login, {
            params: {
                appid: wxConfig.getConfig().appId,
                secret: wxConfig.getConfig().AppSecret,
                js_code: params.code,
                grant_type: 'authorization_code'
            },
        });
        console.log(res.data);
        if (40029 !== res.data.errcode && 40163 !== res.data.errcode) {
            const wxInfo = res.data;

            let user = await this.getUser(wxInfo.openid);
            if (!user && !!params.userInfo) {
                user = await User.create({
                    ...params.userInfo,
                    rememberWords: 0,
                    historyVideoIds: '',
                    historyNews: '',
                    openId: wxInfo.openid
                }, {
                    raw: true,
                });
            }
            setSession(ctx, user);
            ctx.success('登录成功', user);
        } else {
            ctx.errorParams('code 有问题！');
        }
    },

    async getUser(openId) {
        const user = await User.findOne(
            {
                where: {
                    openId: openId
                },
                raw: true,
            }
        );

        return user;
    },
    async getUsersInfo(ctx) {
        const params = getRequestParams(ctx);
        const user = await User.findOne(
            {
                where: {
                    id: params.id
                },
                raw: true,
            }
        );

        ctx.success('获取用户信息成功！', {
            ...user,
        });
    },
    async setUserInfo(ctx) {
        const params = ctx.request.body;
        const id = ctx.session.sessionData.id;
        await User.update({
            ...params,
        }, {
            where: {
                id
            },
        });

        const user = await User.findOne({
            where: {
                id,
            },
            raw: true,
        })

        ctx.success('修改成功！', user);
    },
    async getTeachers(ctx) {
        const teachers = await Teacher.findAll(
            {
                raw: true,
            }
        );

        ctx.success('获取老师成功！', [
            ...teachers,
        ]);
    }
};


module.exports = {
    usersModel,
    User,
};